
package com.zzh.partnersys.chat.server;

import com.zzh.partnersys.chat.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.net.SocketAddress;
import java.nio.charset.Charset;

@Slf4j
@Configuration
public class NettyWebSocketServer {
    public static final int WEB_SOCKET_PORT = 10001;
    // �����̳߳�ִ����
    private EventLoopGroup bossGroup = new NioEventLoopGroup(2);
    private EventLoopGroup workerGroup = new NioEventLoopGroup(NettyRuntime.availableProcessors());

    private LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.INFO);//��־������Handler

    /**
     * ���� ws server
     *
     * @return
     * @throws InterruptedException
     */

    @PostConstruct
    public void start() throws InterruptedException {
//        run();
    }


    /**
     * ��??
     */

    @PreDestroy
    public void destroy() {
        Future<?> future = bossGroup.shutdownGracefully();
        Future<?> future1 = workerGroup.shutdownGracefully();
        future.syncUninterruptibly();
        future1.syncUninterruptibly();
        log.info("�ر� ws server �ɹ�");
    }

    public void run() throws InterruptedException {
        LoginRequestBindMessageHandler LOGIN_BIND_HANDLER = new LoginRequestBindMessageHandler();//��
        LoginRequestNotBindMessageHandler LOGIN_NOT_BIND_HANDLER = new LoginRequestNotBindMessageHandler();//���
        ChatRequestMessageHandler CHAT_MESSAGE_ONE_HANDLER = new ChatRequestMessageHandler();//˽��
        ApplyAddFriendRequestMessageHandler APPLY_ADD_FRIEND_HANDLER = new ApplyAddFriendRequestMessageHandler();//�����������
        ApplyAddFriendResponseMessageHandler APPLY_ADD_FRIEND_RESPONSE_HANDLER = new ApplyAddFriendResponseMessageHandler();//�����������ظ�
        TeamChatRequestMessageHandler TEAM_CHAT_HANDLER = new TeamChatRequestMessageHandler();//����Ⱥ��
        ChatEmojiRequestMessageHandler CHAT_EMOJI_HANDLER = new ChatEmojiRequestMessageHandler();//����Ⱥ��
        TeamChatEmojiRequestMessageHandler TEAM_CHAT_EMOJI_HANDLER = new TeamChatEmojiRequestMessageHandler();//����Ⱥ��

        // ����������������??
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(LOGGING_HANDLER)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //��Ϊ����httpЭ�� ʹ��http�ı������ͽ�����
                        pipeline.addLast("HttpServerCodec",new HttpServerCodec())
                                //�Կ鷽ʽ??���ChunkedWriteHandler����??
                                .addLast("ChunkedWriteHandler", new ChunkedWriteHandler())
                                //http��������л�ֶ� HttpObjectAggregator���Խ�����ξۺ�
                                //�����Ϊʲô������������ʹ�������ʱ���ͻᷢ���http����
                                .addLast("HttpObjectAggregator",new HttpObjectAggregator(8192))
                                //��Ӧwebsocket ������������??WebSocketFrame)��ʽ��??
                                //���������ʱws://localhost:7000/chat/userId=1��ʾ�����uri
                                .addLast(new HttpGetUserIdHandler())//��ȡ�û�����ʱЯ���Ĳ���userId=1������ŵ�channel??
                                //WebSocketServerProtocolHandler�ĺ��Ĺ����ǽ�httpЭ������ΪwsЭ�� �����ֳ�����
                                //��ͨ��һ��״̬�� 101
                                //checkStartsWith : true ���������ӷ���˵�ͬʱ�ſ���Я������
                                .addLast("WebSocketServerProtocolHandler",new WebSocketServerProtocolHandler("/chat", null, true, 8192,false,true))
                                //�Զ����handler��ҵ���߼�����
                                .addLast(new MyTextWebSocketFrameHandler())//����ws����������Ϣ���в��
                                .addLast(LOGIN_BIND_HANDLER)//����󶨵�Handler
                                .addLast(LOGIN_NOT_BIND_HANDLER)//�����󶨵�Handler(�˳���??
                                .addLast(CHAT_MESSAGE_ONE_HANDLER)//����˽�ĵ���??
                                .addLast(APPLY_ADD_FRIEND_HANDLER)//�������������ӵ���??
                                .addLast(APPLY_ADD_FRIEND_RESPONSE_HANDLER)//�������������ӵ���??�ظ�-�ܾ�/ͬ��)
                                .addLast(TEAM_CHAT_HANDLER)//����Ⱥ�ĵ�handler
                                .addLast(CHAT_EMOJI_HANDLER)//�����ı������handler
                                .addLast(TEAM_CHAT_EMOJI_HANDLER);//����Ⱥ�ı������handler
                    }
                });
        //��������??
        ChannelFuture channelFuture = serverBootstrap.bind(WEB_SOCKET_PORT).sync();
    }

}

